<template >
  <div>
    <el-row class="login-container" justify="center" :align="middle">
      <el-card style="max-width: 480px;">
        <template #header>
          <div class="card-header">
            <img :src="imgUrl" alt />
          </div>
        </template>
        <div class="word">后台管理</div>
        <div class="jump-link">
          <el-link type="primary" @click="handleChange" >{{ formType ? '返回登录' : '注册账号' }}</el-link>
        </div>
        <el-form v-if="!formType" 
          ref="loginFromRef"
          :rules="rules"
          :model="loginForm"
          style="max-width: 600px"
          class="demo-ruleForm"
        >
          <el-form-item prop="email">
            <el-input v-model="loginForm.email" placeholder="邮箱" prefix-icon="UserFilled"></el-input>
          </el-form-item>
          <el-form-item v-if="formType" prop="admin">
             <el-input  placeholder="用户名" v-model="loginForm.username" prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="passWoed"
              placeholder="密码"
              prefix-icon="Lock"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="formType" prop="emailCode">
            <el-input  placeholder="验证码" v-model="loginForm.emailCode" prefix-icon="Lock">
              <template #append>
              <span @click="countdwonChange">{{ countdown.vaildText }}</span>
            </template>
          </el-input>
          </el-form-item>

          <el-button v-if="!formType" type="primary" :style="{width: '100%'}" @click="loginFun">登录</el-button>
        </el-form>
        <el-form v-if="formType"
          ref="registerFromRef"
          :rules="rules"
          :model="registerForm"
          style="max-width: 600px"
          class="demo-ruleForm">
          <el-form-item prop="email">
            <el-input v-model="registerForm.email" placeholder="邮箱" prefix-icon="UserFilled"></el-input>
          </el-form-item>
          <el-form-item v-if="formType" prop="admin">
             <el-input  placeholder="用户名" v-model="registerForm.username" prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="密码" v-model="registerForm.password" prefix-icon="Lock" type="passWoed"></el-input>
          </el-form-item>
          <el-form-item v-if="formType" prop="emailCode">
            <el-input  placeholder="验证码" v-model="registerForm.emailCode" prefix-icon="Lock">
              <template #append>
              <el-button @click="getVerificationCode">获取验证码</el-button>
            </template>
          </el-input>
          </el-form-item>
          <el-button v-if="formType" type="primary" :style="{width: '100%'}" @click="registerFun">注册</el-button>
        </el-form>
      </el-card>
    </el-row>
    <!-- <p v-if="errorMessage" class="error">{{ errorMessage }}</p> -->
  </div>
</template>
   <script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { login,fetchCode, register } from "../../api/authApi";
import { ElMessage } from "element-plus";
const imgUrl = new URL("../../../public/sign.png", import.meta.url).href;
const router = useRouter();
//创建切换表单
const formType = ref(0)

//点击切换登陆注册
const handleChange = () => {
  formType.value = formType.value? 0 : 1
}


//发送验证码
const countdown = ref({
  vaildText: '获取验证码',
  timeLeft: 60, // 验证码倒计时秒数
  isCounting: false
})
//登录
const loginFromRef = ref();

//表单数据
const loginForm = reactive({
  password: "",
  email: "",
});

const loginFun = async () => {
  if (loginForm.password == '' || loginForm.email == ''){
    ElMessage.error("邮箱或者密码不能为空");
  }
  try {
    const res = await login(loginForm);
    console.log('login success',res.code);

    if (res.code === 20000)
  {
    ElMessage.success("登录成功");
    localStorage.setItem("token",res.data.token);
    router.push("/start");
  } else{
    ElMessage({
      message: "登录失败",
      type: "error",
      duration: 1000
    })
  }

  } catch (error) {
    console.error("登录错误", error);
    ElMessage({
      message: "登录失败",
      type: "error",
      duration: 1000
    })
  }
};

//注册
const registerFromRef = ref();
const registerForm = reactive({
  email: "",
  username:'',
  password: "",
  emailCode:''
});

// 获取验证码
const getVerificationCode = async () => {
  if (countdown.value.isCounting) return // 如果验证码正在倒计时，就不允许再次点击
  console.log("emailllllll",registerForm.email);
  countdown.value.isCounting = true
  countdown.value.timeLeft = 60
  countdown.value.vaildText = `${countdown.value.timeLeft}s`

  // 启动倒计时
  const interval = setInterval(() => {
    countdown.value.timeLeft--
    countdown.value.vaildText = `${countdown.value.timeLeft}s`
    if (countdown.value.timeLeft <= 0) {
      clearInterval(interval)
      countdown.value.vaildText = '获取验证码'
      countdown.value.isCounting = false
    }
  }, 1000)

  // 发送获取验证码请求
  try {
    const response = await fetchCode({
      email: registerForm.email,
      username: registerForm.username,
      password: registerForm.password
    });
    // 成功获取验证码
    console.log('验证码发送成功', response.data)
  } catch (error) {
    console.error('获取验证码失败', error)
    // 可以在这里处理错误，显示用户错误提示
  }
}

// 注册功能
const registerFun = async () => {
  console.log(registerForm)
  try {
    const response = await register(registerForm); // 使用 await 等待注册的异步结果
    console.log('注册成功', response);

    // 清空表单
    let registerForm = [];

    // 显示成功消息
    ElMessage({
      message: "注册成功",
      type: "success",
      duration: 1000
    });

  } catch (error) {
    // 注册失败时，显示错误消息
    console.error('注册失败', error);
    ElMessage({
      message: "注册失败",
      type: "error",
      duration: 1000
    });
  }
  // register(registerForm)
  //   .then(response => {
  //     console.log('注册成功', response);
  //     registerForm = [];
  //     ElMessage({
  //       message:"注册成功",
  //       type:"success",
  //       duration:1000
  //     });
  //   })
  //   .catch(error => {
  //     console.error('注册失败',error);
  //     ElMessage({
  //       message: "注册失败",
  //       type: "error",
  //       duration:1000
  //     })
  //   }
  //   )

}
//账号校验规则
const validataUser = (rule, value, callback) => {
  //不能为空
  if (value === "") {
    callback(new Error("请输入账号"));
  } 
    // else {
    //   const phoneReg = /^[a-zA-Z0-9_-]{4,16}$/;
    //   phoneReg.test(value)
    //     ? callback
    //     : callback(new Error("格式错误,请输入正确格式"));
    // }
};

//密码校验
const validataPass = (rule, value, callback) => {
  //不能为空
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    const phoneReg = /^[a-zA-Z0-9_-]{4,16}$/;
    phoneReg.test(value)
      ? callback
      : callback(new Error("密码式错误,请输入4-16位字符,请确认格式"));
  }
};

//表单校验
const rules = reactive({
  email: [{ validator: validataUser, trigger: "blur" }],
  password: [{ validator: validataPass, trigger: "blur" }]
});

console.log(loginForm.email, "loginForm.email");

const phoneReg = /^1[3|4|5|7|8][0-9]\d{8}$/;

let flag = false
const countdwonChange = () => {
  if (flag) return;
  //判断邮箱是否正确
  // if (loginForm.email || !phoneReg.test(loginForm.email)) {
  //   return ElMessage({
  //     message: "请检查邮箱是否正确",
  //     type: "warning"
  //   });
  // }
  //倒计时
  setInterval(() =>{
    if(countdown.time <=0 ){
      countdown.time = 120
      countdown.vaildText = `获取验证码`
    }else{
      countdown.time -= 1
      countdown.vaildText = `剩余${countdown.time}s`
    }
    flag = true
  },1000)
};

</script>
   <style lang="less">
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  margin-top: 60px;
  height: 100%;
  .card-header {
    background-color: #dedfdf;
    img {
      width: 318px;
      height: 240px;
    }
  }
  .word {
    font-style: normal;
    font-size: 40px;
    color: rgb(124, 159, 230);
    font-family: "黑体";
    text-align: center;
    font-weight: bold;
    .jump-link {
      text-align: right;
    }
  }
}
</style>